﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using System.Configuration;
using PhotoGallery.Infrastructure.Modules;
using PhotoGallery.Infrastructure.Modules.Configuration;


namespace PhotoGallery.Application
{
    public class PhotoGalleryApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            LoadModules();
        }

        private void LoadModules()
        {
            RouteCollection routes = RouteTable.Routes;
            routes.Clear();
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
            routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");

            ModuleSettings moduleSettings = (ModuleSettings)ConfigurationManager.GetSection(ModuleConstans.ModulesConfigurationSectionName);

            for (int i = moduleSettings.Modules.Count - 1; i > -1; i--)
            {
                ModuleElement module = moduleSettings.Modules[i];

                Type moduleType = Type.GetType(module.FullTypeName);
                if (moduleType == null)
                {
                    throw new TypeLoadException(string.Format("Could not load type '{0}'.", module.FullTypeName));
                }

                IModule moduleInstance = Activator.CreateInstance(moduleType) as IModule;
                if (moduleInstance != null)
                {
                    moduleInstance.Initialize();
                    moduleInstance.RegisterRoutes(routes);
                    moduleInstance.RegisterModelBinders(ModelBinders.Binders);
                }
            }

            //RouteDebug.RouteDebugger.RewriteRoutesForTesting(routes);
        }
    }
}
